import asyncio
import aiohttp
from aiohttp import web

SERVER = "http://127.0.0.1:8000/"

async def fetch(session, **kwargs):
    """
    fetch
    """
    async with session.request(**kwargs) as resp:
        await resp.text()
        return resp

async def client(path, method="GET", headers=None, cookies=None, data=None):
    """
    fetch real server
    """
    _headers = {}
    for key in ['Origin', 'User-Agent', 'Origin', 'Accept', 'Accept-Encoding']:
        if headers.get(key):
            _headers[key] = headers[key]
    headers = _headers
    url = SERVER + path
    async with aiohttp.ClientSession(loop=loop, cookies=cookies, headers=headers) as session:
        return await fetch(session, method=method, url=url, data=data)

async def root(request):
    path = request.match_info['path']
    headers = request.headers
    cookies = request.cookies
    method = request.method
    data = await request.post()
    data = dict(data)
    headers = dict(headers)
    _resp = await client(path=path, method=method, headers=headers, cookies=cookies, data=data)
    status = _resp.status
    if status == 404:
        print("OOO")
    resp = web.Response(content_type=_resp.content_type, status=status)
    resp.text = await _resp.text()
    return resp

def init(loop):
    app = web.Application(loop=loop)
    app.router.add_get(r'/{path:[\s\S]*}', root)
    app.router.add_post(r'/{path:[\s\S]*}', root)
    app.router.add_options(r'/{path:[\s\S]*}', root)
    return app

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    web.run_app(init(loop), port=8081)